package com.captain.lc.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.Objects;

/**
 * @author captain
 * @des:
 * @date 2021/10/9 1:50
 */
public class AddTwoNumbers02 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (Objects.isNull(l1)) return l2;
        if (Objects.isNull(l2)) return l1;
        //解题思路:
        ListNode res = new ListNode(-1);
        ListNode dummy = res;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int l1Val = l1.val;
            int l2Val = l2.val;
            int curTotal = l1Val + l2Val + carry;
            carry = curTotal / 10;
            int cur = curTotal % 10;
            dummy.next = new ListNode(cur);
            dummy = dummy.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        //l1 可能不为null
        if (l1 != null) {
            while (l1 != null) {
                int curTotal = l1.val +  carry;
                carry = curTotal / 10;
                int cur = curTotal % 10;
                dummy.next = new ListNode(cur);
                dummy = dummy.next;
                l1 = l1.next;
            }
        }
        if (l2 != null) {
            while (l2 != null) {
                int curTotal = l2.val +  carry;
                carry = curTotal / 10;
                int cur = curTotal % 10;
                dummy.next = new ListNode(cur);
                dummy = dummy.next;
                l2 = l2.next;
            }
        }

        //查看是否存在进位
        if (carry > 0) {
            dummy.next = new ListNode(carry);
            dummy = dummy.next;
        }
        return res.next;
    }
}
